// pages/supply-menu/supply-menu.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    supplierExpand: false,
    supplierList: [],
    activeTag: '',
    activeTagName: '',
    activeFilter: 1,
    perShow: false,
    params: {
      foodName: '',
      supplierFoodId: '0',
      variety: 1,
      type: "1",
    },
    params2: {
      foodName: '',
      variety: 1,
      type: 2,
    },
    applyType: 0,
    selFoods: [],
    activeNames: ["0", "1"],
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function(options) {
    const departmentType = wx.getStorageSync("departmentType")
    const {
      estimatedTime,
      estimatedNum,
      applyType,
      stockOrderId,
      auxiliaryMaterialsId,
      smallCanteenPurchaseId,
      collarId
    } = app.globalData

    if (applyType==0){
      this.setData({ orderId: stockOrderId})
    } else if (applyType == 1) {
      this.setData({ orderId: auxiliaryMaterialsId})
    } else if (applyType == 2) {
      this.setData({ orderId: smallCanteenPurchaseId})
    } else {
      this.setData({ orderId: collarId})
    }

    if (applyType === 1) {
      this.setData({
        'params.type': "2"
      })
    }
    this.setData({
      applyType,
      estimatedTime,
      estimatedNum,
      departmentType
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getSupplier()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      selFoods: []
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  onInput(e) {
    this.setData({
      'params.foodName': e.detail.value
    })
  },

  toSearch() {

    this.getFoods()
    this.setData({

    }, () => {

    })
  },
  showPer() {
    this.setData({
      perShow: true
    })
  },
  onClose() {
    this.setData({
      perShow: false
    })
  },
  onPerConfirm(e) {
    console.log(e)
    const {
      supplierId,
      supplierName
    } = e.detail.value

    this.setData({
      perShow: false,
      activeTag: supplierId,
      activeTagName: supplierName,
      'params.supplierFoodId': supplierId
    }, () => {
      this.getFoods()
    })
  },
  //获取供应商列表
  getSupplier() {
    app.reqFetch.getSupplier({}, (res) => {
      const
        list = res
      if (list) {
        this.setData({
          supplierList: list,
          activeTag: list[0].supplierId,
          activeTagName: list[0].supplierName,
          supplierName: list[0].supplierName,
          'params.supplierFoodId': list[0].supplierId
        }, () => this.getFoods())
      }
    })
  },

  changeCollapse(event) {
    console.log(event.detail)
    this.setData({
      activeNames: event.detail
    });
  },
  selSupplier(e) {
    const {
      none,
      supplierId,
      supplierName
    } = e.currentTarget.dataset.record

    this.setData({
      activeTag: supplierId,
      activeTagName: supplierName,
      'params.supplierFoodId': supplierId
    }, () => {
      this.getFoods()
    })

  },

  selFilter(e) {
    const {
      selFoods
    } = this.data
    this.setData({
      selFoods
    })
    const {
      key
    } = e.currentTarget.dataset
    this.setData({
      activeFilter: key,
      'params.variety': key,
      'params2.variety': key
    }, () => this.getFoods())
  },
  getFoods() {
    const {
      applyType, params, params2
    } = this.data
    if (app.globalData.revise) {
      params.orderId = this.data.orderId
      params2.orderId = this.data.orderId
    }
    if (applyType === 3) {
      app.reqFetch.selectFoodmx({
        ...this.data.params2,
        sign: applyType
      }, (res) => {
        this.setList(res)
      })
    } else {
      app.reqFetch.supplierFoodId({
        ...this.data.params,
        sign: applyType
      }, (res) => {
        this.setList(res)
      })
    }
  },
  setList(res){



    this.setData({
      foodList: res,
      checked: false
    }, () => {
      const {
        selFoods
      } = this.data
      this.setData({
        selFoods
      })

    })
  },


  
  checkItem(e) {
   
    let { foodList } = this.data
    const foodItem = e.currentTarget.dataset.record
    foodList.map(item => {
      if (item.foodId === foodItem.foodId) item.flag = e.detail?1:0
    })
    this.setData({ foodList },()=>{
      if (e.detail) {
        this.addFood(foodItem)
      } else {
        console.log(1)
        this.delFood(foodItem)
      }
    })
    this.setData({
      selFoods: e.detail
    });

  },
  addFood(foodItem) {
    const { supplierId, supplierName, foodId, unit, purchaseNum } = foodItem
    const { applyType } = this.data
    let params = {
      sign: applyType,
      foodId,
      supplierId,
      unit,
      purchaseNum }
    if (app.globalData.revise){
      params.orderId = this.data.orderId
    }
    app.reqFetch.saveFood({
      ...params,
    }, (res) => {
    }) 
    var menuList = wx.getStorageSync('menuList')||[]
    let t = menuList.filter(item => item.supplierId === foodItem.supplierId)
    if (t.length === 0) {
      menuList.push({
        supplierId: supplierId,
        supplierName: applyType === 3 ? '主食领取列表' : supplierName,
        foods: [foodItem],
      })
    }else{
      menuList.map(item =>{
        if (item.supplierId === supplierId){
          item.foods.push(foodItem)
        }
      })
    }
    console.log(menuList)
     wx.setStorageSync('menuList', menuList)
   
  },
  delFood(foodItem){
    const { supplierId, supplierName, foodId } = foodItem
    const { applyType } = this.data
    let params = {
      sign: applyType,
      foodId,
      supplierId,}
    if (app.globalData.revise) {
      params.orderId = this.data.orderId
    }
    app.reqFetch.deleteFood({
      ...params
    }, (res) => {
    })
  },

  updataFood(foodItem,val) {
    const { applyType } = this.data
    if (foodItem.flag===1){
        let params={
          sign: applyType,
          foodId: foodItem.foodId,
          supplierId: foodItem.supplierId,
          purchaseNum: val
        }
      if (app.globalData.revise) {
        params.orderId = this.data.orderId
      }
      app.reqFetch.updateFood({
       ...params
      }, (res) => {
      })
    }    
  },
  recordFood(foodItem){
    const { supplierId, supplierName, foodId } = foodItem
    var flag=false
    var menuList = wx.getStorageSync('menuList') || [] 
    menuList.map(item=>{
      if (item.supplierId === supplierId){
        item.foods.map(ele=>{
          if (ele.foodId === foodId){
            flag=true
          }
        })
      }
    })
    return flag

  },




  filterFoodArr(arr1, arr2) {

    if (arr1 > arr2) {
      var larger = arr1
      var smaller = arr2

    } else {
      var larger = arr2
      var smaller = arr1
    }
    var id = ''
    larger.map(item => {
      if (arr2.indexOf(item) === -1) {
        id = item
      }
    })

    return id
  },

  checkAll(e) {
    this.setData({
      checked: e.detail
    });
    const {
      foodList
    } = this.data
    var arr = []
    if (e.detail) {
      foodList.map(item => {
        arr.push(item.supplierId + ',' + item.foodId)
      })
      this.setData({
        selFoods: arr
      });

    } else {
      //
      this.setData({
        selFoods: []
      });
    }
  },

  changeNum(e) {                                                                                                                                                                                                                                                                                                
    const {
      foodId
    } = e.currentTarget.dataset.record

    this.updataFood(e.currentTarget.dataset.record, e.detail)
    let {
      foodList
    } = this.data
    foodList.map(item => {
      if (item.foodId === foodId) {
     
     
   
        item.purchaseNum = e.detail
      }
    })
    this.setData({
      foodList
    })
  },

  toMenu() {
    wx.navigateTo({
      url: '/pages/purchase-list/purchase-list',
    })
  },
  toSearchPage(){
    wx.navigateTo({
      url: '/pages/supply-search/supply-search',
    })
  },
  handleCancel() {
    wx.navigateBack({
      delta: 1,
    })
  },

  pivot(arr) {
    for (var i in arr) {
      for (var j in arr) {
        if (arr[i].foodId == arr[j].foodId && i != j) {
          arr[i].purchaseNum = arr[i].purchaseNum += arr[j].purchaseNum
          arr.splice(j, 1)
        } else {
          arr[i]
        }
      }
    }
    return arr
  },

    handleCancel() {
    const { applyType, } = app.globalData
    if (applyType === 1) {
      wx.reLaunch({
        url: '/pages/warehouse-home/warehouse-home?data=' + JSON.stringify({ type: applyType }),
      })
    } else {
      wx.reLaunch({
        url: '/pages/chef-home/chef-home?data=' + JSON.stringify({ type: applyType }),
      })
    }



  }
})